<template>
    <div id="topbar">
      <div class="file_upload_box">
        <input id="uploadBtn" type="file" @change="loadExcel" />
        <a href="#none">上传文件</a>
      </div>
      <!-- <select v-model="selected" @change="selectExcel">
        <option disabled value="">Choose</option>
        <option v-for="option in options" :key="option.text" :value="option.value">
          {{ option.text }}
        </option>
      </select> -->
      <div>
        <a-button size="larger" @click="downloadExcel" style="margin-left: 300px; margin-top: 10px;">下载到本地</a-button>
      </div>
      <div>
        <a-button @click="save" style="margin-left: 800px; margin-top: 10px;">保存</a-button>
      </div>
    </div>
    <div id="luckysheet"></div>
    <div v-show="isMaskShow" id="tip">Downloading</div>

    <a-modal v-bind:open="visible" @ok="handleSave" @cancel="handleCancel" :confirm-loading="confirmLoading">
      <a-form
            :model="formState"
            :rules="rules"
            name="basic"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 14 }"
            autocomplete="off"
            @finish="handleSave"
        >
            <a-form-item
                label="角色名"
                name="characterName"
            >
                <a-input v-model:value="formState.characterName" placeholder="角色名"/>
            </a-form-item>
            <a-form-item
                label="角色唯一标识名"
                name="name"
            >
                <a-input v-model:value="formState.name" placeholder="角色唯一标识名，不可与其他角色的唯一标识名重复"/>
            </a-form-item>
            <a-form-item
                label="骰娘记录属性"
                name="rememberedVars"
            >
                <a-textarea v-model:value="formState.rememberedVars" placeholder="骰娘记录属性"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 10 }">
                <a-button type="primary" html-type="submit">保存</a-button>
            </a-form-item>
        </a-form>
        <template #footer>
        </template>
    </a-modal>
  </template>
  
  <script lang="js" setup>
  import { reactive, ref, onMounted } from 'vue'
  import { exportExcel, saveExcel } from './export'
  import LuckyExcel from 'luckyexcel'
  import { saveCharacter } from '../../api/character_api'
  
  const isMaskShow = ref(false)
  const selected = ref('')
  const jsonData = ref({})
  const options = ref([
    { text: 'Money Manager.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/money-manager-2.xlsx' },
    {
      text: 'Activity costs tracker.xlsx',
      value: 'https://minio.cnbabylon.com/public/luckysheet/Activity%20costs%20tracker.xlsx'
    },
    {
      text: 'House cleaning checklist.xlsx',
      value: 'https://minio.cnbabylon.com/public/luckysheet/House%20cleaning%20checklist.xlsx'
    },
    {
      text: 'Student assignment planner.xlsx',
      value: 'https://minio.cnbabylon.com/public/luckysheet/Student%20assignment%20planner.xlsx'
    },
    {
      text: 'Credit card tracker.xlsx',
      value: 'https://minio.cnbabylon.com/public/luckysheet/Credit%20card%20tracker.xlsx'
    },
    { text: 'Blue timesheet.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Blue%20timesheet.xlsx' },
    {
      text: 'Student calendar (Mon).xlsx',
      value: 'https://minio.cnbabylon.com/public/luckysheet/Student%20calendar%20%28Mon%29.xlsx'
    },
    {
      text: 'Blue mileage and expense report.xlsx',
      value: 'https://minio.cnbabylon.com/public/luckysheet/Blue%20mileage%20and%20expense%20report.xlsx'
    }
  ])
  const name = ref("")
  const visible = ref(false)
  const formState = reactive({// 表格对象
    id: props.id,  
    characterName: '',
    name: '',
    rememberedVars: '',
  });
  const rules = { // 表格校验规则
    characterName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
    name: [{required: true, message:'请输入唯一角色名', trigger: 'blur'}],
  };

  const loadExcelFromUrl = (url) => {
    let file = null
    getFileFromUrl(url,"tmp.xlsx")
    .then((response)=>{
        file = response
        LuckyExcel.transformExcelToLucky(file, function (exportJson, luckysheetfile) {
          if (exportJson.sheets == null || exportJson.sheets.length == 0) {
            alert('Failed to read the content of the excel file, currently does not support xls files!')
            return
          }
          console.log('exportJson', exportJson)
          jsonData.value = exportJson
      
          window.luckysheet.destroy()
      
          window.luckysheet.create({
            container: 'luckysheet', //luckysheet is the container id
            showinfobar: false,
            data: exportJson.sheets,
            title: exportJson.info.name,
            userInfo: exportJson.info.name.creator
          })
        })
    })
    .catch((e)=>{
      console.error(e)
    });
  }

  const loadExcel = (evt) => {
    const files = evt.target.files
    console.log(files[0])
    if (files == null || files.length == 0) {
      alert('No files wait for import')
      return
    }
  
    let name = files[0].name
    let suffixArr = name.split('.'),
    suffix = suffixArr[suffixArr.length - 1]
    if (suffix != 'xlsx') {
      alert('Currently only supports the import of xlsx files')
      return
    }
    LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert('Failed to read the content of the excel file, currently does not support xls files!')
        return
      }
      console.log('exportJson', exportJson)
      jsonData.value = exportJson
  
      window.luckysheet.destroy()
  
      window.luckysheet.create({
        container: 'luckysheet', //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator
      })
    })
  }

  // const loadExcel = (info: UploadChangeParam) => {
  //   let name = info.file.name
  //   let suffixArr = name.split('.'),
  //     suffix = suffixArr[suffixArr.length - 1]
  //   if (suffix != 'xlsx') {
  //     alert('Currently only supports the import of xlsx files')
  //     return
  //   }
  //   LuckyExcel.transformExcelToLucky(info.file, function (exportJson, luckysheetfile) {
  //     if (exportJson.sheets == null || exportJson.sheets.length == 0) {
  //       alert('Failed to read the content of the excel file, currently does not support xls files!')
  //       return
  //     }
  //     console.log('exportJson', exportJson)
  //     jsonData.value = exportJson
  
  //     window.luckysheet.destroy()
  
  //     window.luckysheet.create({
  //       container: 'luckysheet', //luckysheet is the container id
  //       showinfobar: false,
  //       data: exportJson.sheets,
  //       title: exportJson.info.name,
  //       userInfo: exportJson.info.name.creator
  //     })
  //   })
  // }
  
  const selectExcel = (evt) => {
    const value = selected.value
    const name = evt.target.options[evt.target.selectedIndex].innerText
  
    if (value == '') {
      return
    }
    isMaskShow.value = true
  
    LuckyExcel.transformExcelToLuckyByUrl(value, name, (exportJson, luckysheetfile) => {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert('Failed to read the content of the excel file, currently does not support xls files!')
        return
      }
      console.log('exportJson', exportJson)
      jsonData.value = exportJson
  
      isMaskShow.value = false
      window.luckysheet.destroy()
  
      window.luckysheet.create({
        container: 'luckysheet', //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator
      })
    })
  }
  const downloadExcel = () => {
    // const value = selected.value;;
    //
    // if(value.length==0){
    //     alert("Please select a demo file");
    //     return;
    // }
    //
    // var elemIF = document.getElementById("Lucky-download-frame");
    // if(elemIF==null){
    //     elemIF = document.createElement("iframe");
    //     elemIF.style.display = "none";
    //     elemIF.id = "Lucky-download-frame";
    //     document.body.appendChild(elemIF);
    // }
    // elemIF.src = value;
    exportExcel(luckysheet.getAllSheets(), '下载')
  }

  const save = () => {
    visible.value = true
  }

  const handleSave = (value) => {
    saveCharacter(formState)
    .then(resp => {
      saveExcel(luckysheet.getAllSheets(), rest.data)
      visible.value = false
    })
  }

  const handleCancel= () => {
    visible.value = false
  }
  
  const getFileFromUrl= (url, fileName) => {
    return new Promise((resolve, reject) => {
        var blob = null;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.setRequestHeader('Accept', 'image/png');
        xhr.responseType = "blob";
        // 加载时处理
        xhr.onload = () => {
          // 获取返回结果
            blob = xhr.response;
            let file= new File([blob], fileName, { type: 'image/png' });
            // 返回结果
            resolve(file);
        };
        xhr.onerror = (e) => {
            reject(e)
        };
        // 发送
        xhr.send();
    });
  }

  // !!! create luckysheet after mounted
  onMounted(() => {
    luckysheet.create({
      container: 'luckysheet'
    })
    console.log(props.id)
    // loadExcelFromUrl("http://119.45.201.47:9000/trpg//character/2192307728105472/16.xlsx?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20240128%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20240128T032005Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&x-id=GetObject&X-Amz-Signature=e5697a0fd9ca96a341906fea422d03991db38b4cbd63bdc23b253bd242742dc7")
  })
  </script>
  
  <style  scoped>
  #luckysheet {
    margin: 0px;
    padding: 0px;
    width:  1660px;
    left: 0px;
    top: 30px;
    bottom: 0px;
    position: absolute;
    margin-left: 258px;
    margin-top: 100px;
  }
  
  #uploadBtn {
    font-size: 16px;
  }
  
  #tip {
    position: absolute;
    z-index: 1000000;
    left: 0px;
    top: 0px;
    bottom: 0px;
    right: 0px;
    background: rgba(255, 255, 255, 0.8);
    text-align: center;
    font-size: 40px;
    align-items: center;
    justify-content: center;
    display: flex;
  }

  #topbar{
    display: grid; 
    grid-template-columns: 15% 15% 70%;
    grid-template-rows: 100%;

  }

.file_upload_box {
    display: inline-block;
    width: 200px;
    height: 60px;
    position: relative;
    overflow: hidden;
}
.file_upload_box input[type=file] {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    line-height: 60px;
    opacity: 0;
    cursor: pointer;
}
.file_upload_box a {
    display: inline-block;
    width: 100%;
    line-height: 45px;
    text-align: center;
    font-family: "Microsoft yahei";
    color: black;
    font-weight: 700;
    text-decoration: none;
}
  </style>